<template>
  <div class="transfer-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>传输队列</h2>
      <p>实时监控文件上传和下载任务</p>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="16" class="stats-cards">
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <el-icon :size="32" color="#409eff"><Upload /></el-icon>
            <div class="stat-content">
              <div class="stat-value">{{ stats.uploading }}</div>
              <div class="stat-label">正在上传</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <el-icon :size="32" color="#67c23a"><Download /></el-icon>
            <div class="stat-content">
              <div class="stat-value">{{ stats.downloading }}</div>
              <div class="stat-label">正在下载</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <el-icon :size="32" color="#e6a23c"><Clock /></el-icon>
            <div class="stat-content">
              <div class="stat-value">{{ stats.waiting }}</div>
              <div class="stat-label">等待中</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <el-icon :size="32" color="#f56c6c"><Warning /></el-icon>
            <div class="stat-content">
              <div class="stat-value">{{ stats.failed }}</div>
              <div class="stat-label">失败</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button-group>
          <el-button
            :type="statusFilter === '' ? 'primary' : 'default'"
            @click="statusFilter = ''; loadTasks()"
          >
            全部 ({{ totalTasks }})
          </el-button>
          <el-button
            :type="statusFilter === 'uploading' ? 'primary' : 'default'"
            @click="statusFilter = 'uploading'; loadTasks()"
          >
            上传中 ({{ stats.uploading }})
          </el-button>
          <el-button
            :type="statusFilter === 'downloading' ? 'primary' : 'default'"
            @click="statusFilter = 'downloading'; loadTasks()"
          >
            下载中 ({{ stats.downloading }})
          </el-button>
          <el-button
            :type="statusFilter === 'completed' ? 'primary' : 'default'"
            @click="statusFilter = 'completed'; loadTasks()"
          >
            已完成
          </el-button>
          <el-button
            :type="statusFilter === 'failed' ? 'primary' : 'default'"
            @click="statusFilter = 'failed'; loadTasks()"
          >
            失败 ({{ stats.failed }})
          </el-button>
        </el-button-group>
      </div>
      <div class="toolbar-right">
        <el-button :icon="Refresh" @click="loadTasks">刷新</el-button>
        <el-button :icon="Delete" @click="handleClearCompleted">清空已完成</el-button>
      </div>
    </div>

    <!-- 传输任务列表 -->
    <div class="transfer-list" v-loading="loading">
      <el-empty v-if="!tasks.length" description="暂无传输任务" />

      <el-card
        v-for="task in tasks"
        :key="task.id"
        class="transfer-item"
        shadow="hover"
      >
        <div class="task-header">
          <div class="task-info">
            <el-icon :size="24" :color="getTaskIconColor(task)">
              <component :is="getTaskIcon(task)" />
            </el-icon>
            <div class="task-details">
              <div class="task-name">{{ task.file_name }}</div>
              <div class="task-meta">
                <span class="task-size">{{ formatFileSize(task.file_size) }}</span>
                <span class="task-separator">•</span>
                <span class="task-user">{{ task.username }}</span>
                <span class="task-separator">•</span>
                <span class="task-time">{{ formatTime(task.created_at) }}</span>
              </div>
            </div>
          </div>
          <div class="task-actions">
            <el-tag :type="getStatusTagType(task.status)" size="small">
              {{ getStatusText(task.status) }}
            </el-tag>
            <el-button-group style="margin-left: 12px">
              <el-button
                v-if="task.status === 'paused'"
                size="small"
                type="primary"
                :icon="VideoPlay"
                @click="handleResume(task)"
              >
                继续
              </el-button>
              <el-button
                v-if="['uploading', 'downloading'].includes(task.status)"
                size="small"
                type="warning"
                :icon="VideoPause"
                @click="handlePause(task)"
              >
                暂停
              </el-button>
              <el-button
                v-if="task.status === 'failed'"
                size="small"
                type="primary"
                :icon="Refresh"
                @click="handleRetry(task)"
              >
                重试
              </el-button>
              <el-button
                v-if="!['completed', 'cancelled'].includes(task.status)"
                size="small"
                type="danger"
                :icon="Close"
                @click="handleCancel(task)"
              >
                取消
              </el-button>
              <el-button
                v-if="['completed', 'failed', 'cancelled'].includes(task.status)"
                size="small"
                :icon="Delete"
                @click="handleDelete(task)"
              >
                删除
              </el-button>
            </el-button-group>
          </div>
        </div>

        <div class="task-progress">
          <el-progress
            :percentage="task.progress"
            :status="getProgressStatus(task)"
            :stroke-width="12"
          >
            <template #default="{ percentage }">
              <span class="progress-text">
                {{ percentage }}%
                <span v-if="['uploading', 'downloading'].includes(task.status)" class="progress-speed">
                  {{ formatSpeed(task.speed) }}
                </span>
              </span>
            </template>
          </el-progress>
        </div>

        <div class="task-footer" v-if="task.status !== 'completed'">
          <span class="task-progress-detail">
            已传输: {{ formatFileSize(task.transferred) }} / {{ formatFileSize(task.file_size) }}
          </span>
          <span v-if="task.estimated_time" class="task-eta">
            预计剩余: {{ formatDuration(task.estimated_time) }}
          </span>
        </div>

        <div class="task-error" v-if="task.status === 'failed' && task.error_message">
          <el-alert
            :title="task.error_message"
            type="error"
            :closable="false"
            show-icon
          />
        </div>
      </el-card>
    </div>

    <!-- 分页 -->
    <div class="pagination" v-if="totalTasks > pageSize">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="totalTasks"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Upload,
  Download,
  Clock,
  Warning,
  Refresh,
  Delete,
  VideoPlay,
  VideoPause,
  Close,
  ArrowUp,
  ArrowDown
} from '@element-plus/icons-vue'
import axios from '@/api'
import io from 'socket.io-client'

// 数据状态
const loading = ref(false)
const tasks = ref([])
const statusFilter = ref('')
const stats = reactive({
  uploading: 0,
  downloading: 0,
  waiting: 0,
  failed: 0
})

// 分页
const currentPage = ref(1)
const pageSize = ref(20)
const totalTasks = ref(0)

// WebSocket连接
let socket = null

// 生命周期
onMounted(() => {
  loadTasks()
  loadStats()
  connectWebSocket()

  // 定期刷新数据
  const refreshInterval = setInterval(() => {
    loadTasks()
    loadStats()
  }, 5000)

  // 组件卸载时清理
  onUnmounted(() => {
    clearInterval(refreshInterval)
    if (socket) {
      socket.disconnect()
    }
  })
})

// WebSocket连接
const connectWebSocket = () => {
  const token = localStorage.getItem('token')
  // 生产环境使用当前域名，开发环境使用指定地址
  const socketUrl = import.meta.env.VITE_API_BASE_URL || 
                   (import.meta.env.MODE === 'production' ? window.location.origin : 'http://drive.kbin.cc:3000')
  socket = io(socketUrl, {
    auth: { token }
  })

  socket.on('connect', () => {
    console.log('WebSocket连接成功')
  })

  socket.on('transfer:progress', (data) => {
    // 更新任务进度
    const task = tasks.value.find(t => t.id === data.taskId)
    if (task) {
      task.progress = data.progress
      task.transferred = data.transferred
      task.speed = data.speed
      task.estimated_time = data.estimatedTime
    }
  })

  socket.on('transfer:status', (data) => {
    // 更新任务状态
    const task = tasks.value.find(t => t.id === data.taskId)
    if (task) {
      task.status = data.status
      if (data.error) {
        task.error_message = data.error
      }
    }
    loadStats()
  })

  socket.on('disconnect', () => {
    console.log('WebSocket断开连接')
  })
}

// 方法
const loadTasks = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/transfers', {
      params: {
        page: currentPage.value,
        limit: pageSize.value,
        status: statusFilter.value
      }
    })
    tasks.value = response.data.data.tasks || []
    totalTasks.value = response.data.data.total || 0
  } catch (error) {
    console.error('加载传输任务失败:', error)
    ElMessage.error('加载传输任务失败')
  } finally {
    loading.value = false
  }
}

const loadStats = async () => {
  try {
    const response = await axios.get('/api/transfers/stats')
    Object.assign(stats, response.data.data)
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

const handlePause = async (task) => {
  try {
    await axios.post(`/api/transfers/${task.id}/pause`)
    ElMessage.success('任务已暂停')
    loadTasks()
  } catch (error) {
    console.error('暂停失败:', error)
    ElMessage.error('暂停失败')
  }
}

const handleResume = async (task) => {
  try {
    await axios.post(`/api/transfers/${task.id}/resume`)
    ElMessage.success('任务已继续')
    loadTasks()
  } catch (error) {
    console.error('继续失败:', error)
    ElMessage.error('继续失败')
  }
}

const handleCancel = async (task) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消传输 "${task.file_name}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await axios.post(`/api/transfers/${task.id}/cancel`)
    ElMessage.success('任务已取消')
    loadTasks()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消失败:', error)
      ElMessage.error('取消失败')
    }
  }
}

const handleRetry = async (task) => {
  try {
    await axios.post(`/api/transfers/${task.id}/retry`)
    ElMessage.success('任务已重新开始')
    loadTasks()
  } catch (error) {
    console.error('重试失败:', error)
    ElMessage.error('重试失败')
  }
}

const handleDelete = async (task) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除任务 "${task.file_name}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await axios.delete(`/api/transfers/${task.id}`)
    ElMessage.success('任务已删除')
    loadTasks()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleClearCompleted = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有已完成的任务吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await axios.post('/api/transfers/clear-completed')
    ElMessage.success('已清空')
    loadTasks()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空失败:', error)
      ElMessage.error('清空失败')
    }
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  loadTasks()
}

const handlePageChange = (val) => {
  currentPage.value = val
  loadTasks()
}

// 工具函数
const getTaskIcon = (task) => {
  return task.transfer_type === 'upload' ? ArrowUp : ArrowDown
}

const getTaskIconColor = (task) => {
  if (task.status === 'completed') return '#67c23a'
  if (task.status === 'failed') return '#f56c6c'
  if (task.transfer_type === 'upload') return '#409eff'
  return '#67c23a'
}

const getStatusText = (status) => {
  const statusMap = {
    waiting: '等待中',
    uploading: '上传中',
    downloading: '下载中',
    paused: '已暂停',
    completed: '已完成',
    failed: '失败',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

const getStatusTagType = (status) => {
  const typeMap = {
    waiting: 'info',
    uploading: 'primary',
    downloading: 'success',
    paused: 'warning',
    completed: 'success',
    failed: 'danger',
    cancelled: 'info'
  }
  return typeMap[status] || 'info'
}

const getProgressStatus = (task) => {
  if (task.status === 'completed') return 'success'
  if (task.status === 'failed') return 'exception'
  if (task.status === 'paused') return 'warning'
  return null
}

const formatFileSize = (bytes) => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
}

const formatSpeed = (bytesPerSecond) => {
  if (!bytesPerSecond) return '0 B/s'
  return formatFileSize(bytesPerSecond) + '/s'
}

const formatDuration = (seconds) => {
  if (!seconds) return '-'
  if (seconds < 60) return `${Math.round(seconds)}秒`
  if (seconds < 3600) return `${Math.round(seconds / 60)}分钟`
  return `${Math.round(seconds / 3600)}小时`
}

const formatTime = (time) => {
  if (!time) return '-'
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}`
}
</script>

<style scoped>
.transfer-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.page-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 16px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.page-header p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.stats-cards {
  margin-bottom: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.toolbar {
  background: white;
  padding: 16px 20px;
  border-radius: 8px;
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.toolbar-left {
  display: flex;
  gap: 8px;
}

.toolbar-right {
  display: flex;
  gap: 8px;
}

.transfer-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.transfer-item {
  background: white;
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.task-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.task-details {
  flex: 1;
}

.task-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.task-meta {
  font-size: 13px;
  color: #999;
}

.task-separator {
  margin: 0 8px;
}

.task-actions {
  display: flex;
  align-items: center;
}

.task-progress {
  margin-bottom: 12px;
}

.progress-text {
  font-size: 13px;
  font-weight: 500;
}

.progress-speed {
  margin-left: 8px;
  color: #409eff;
}

.task-footer {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
  color: #666;
}

.task-error {
  margin-top: 12px;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
  background: white;
  padding: 16px 20px;
  border-radius: 8px;
}
</style>
